import { useEffect, useState, useRef } from "react"
import { Button, Form, message, Image, Spin } from 'antd'
import style from './index.module.less'
import UserSearch from "../UserSearch"
import { saveExam, getEntryExamInfo, editExam } from '@/services/entryExam'
import type { UploadFile } from 'antd/es/upload/interface';
import FingerInput from "../FingerInput"
import Editor from "../Editor"
import useTemplate from "@/hooks/useTemplate"
import { STATUS_CODE } from '@/common/const'
import { exportWord } from '@/utils/download'

enum STEP {
    ID,
    CONTENT
}
type Props = {
    readonly: boolean;
    id: string | null;
    onSave: () => void;
    type: 'rjtj' | 'ndtj'
}
export default (props: Props) => {
    const { readonly, id, onSave, type } = props
    const [step, setStep] = useState(STEP.ID)
    const [patientNumber, setPatientnumber] = useState('')
    const editorRef = useRef<any>(null)
    const [loading, setLoading] = useState(false)
    const [tjImgs, setTjImgs] = useState<UploadFile[]>([]);
    const [rjImgs, setRjImgs] = useState<UploadFile[]>([]);
    const [requestLoading, setRequestLoading] = useState(false)
    const [fingerUrl, setFingerUrl] = useState('') // 患者指纹
    const [template, setTemplate, getTemplate, stepLoading, blId, setBlId] = useTemplate()

    useEffect(() => {
        if (id) {
            setStep(STEP.CONTENT)
            getData()
        }
    }, [id])

    const handleFinish = async (value) => {
        setPatientnumber(value.patientnumber);
        await getTemplate(type, value.patientnumber)
        setStep(STEP.CONTENT)
    }

    const getData = async () => {
        setRequestLoading(true)
        const { code, data } = await getEntryExamInfo({ recordId: id })
        if (code === STATUS_CODE.SUCCESS) {
            setTemplate(data.bl?.content)
            setTjImgs(data.jyjg?.tjjg)
            setRjImgs(data.jyjg?.rjzp)
            setBlId(data.bl?.blId)
        }
        setRequestLoading(false)
    }

    const handleClick = async () => {
        setLoading(true)
        if (!readonly) {
            await handleSave()
        } else {
            await handleExport()
        }
        setLoading(false)
    }

    const handleExport = () => {
        exportWord(template, '体检结果导出.docx')
    }
    const handleSave = async () => {
        const html = editorRef.current?.getHtml();
        let data = {
            patientNumber,
            content: html,
            type,
            templateId: type,
            blId,
            signature: fingerUrl,
        }
        try {
            if (id) {
                await editExam(data)
            } else {
                await saveExam(data)
            }
            message.success('保存成功')
        } catch (error) {
            message.error('保存失败')
        } finally {
            onSave();
        }

    }

    const ImgContainer = ({ imgs }) => {
        return (<div className={style.imgContainer}>
            {imgs?.map((item) => <Image key={item.id} src={item.url} width={100} height={100} />)}
        </div>)
    }

    const handleFinishInput = (url) => {
        setFingerUrl(url)
    }

    return (
        <>
            {
                step === STEP.ID ? <div className={style.findUser}>
                    <Form
                        name="basic"
                        labelCol={{ span: 8 }}
                        style={{ width: 800 }}
                        onFinish={handleFinish}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="姓名/胸牌号"
                            name="patientnumber"
                            rules={[{ required: true, message: '请输入姓名/胸牌号' }]}
                        >
                            <UserSearch />
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit" loading={stepLoading}>
                                下一步
                            </Button>
                        </Form.Item>
                    </Form>
                </div> :
                    <Spin spinning={requestLoading}>
                        <div className={style.content}>
                            <div className={style.editor}>
                                <div className={style.title}>体检基本信息</div>
                                <Editor content={template} ref={editorRef} readonly={readonly} />
                            </div>
                            <div className={style.fingers}>
                                {fingerUrl ? <div className={style.finger}>
                                    患者指纹：
                                    <img src={fingerUrl} alt="" />
                                </div> : null}
                            </div>
                            {readonly && <div className={style.upload}>
                                {
                                    tjImgs?.length ? <div className={style.result}>
                                        <div className={style.title}>体检结果</div>
                                        {<ImgContainer imgs={tjImgs} />}
                                    </div> : null
                                }
                                {
                                    rjImgs?.length ? <div className={style.entryPic}>
                                        <div className={style.title}>入监照片</div>
                                        {readonly && <ImgContainer imgs={rjImgs} />}
                                    </div> : null
                                }
                            </div>}
                            <div className={style.save}>
                                {readonly ? null : <> <FingerInput onFinish={handleFinishInput} btnText={'录入患者指纹'} />
                                </>}
                                <Button type="primary" onClick={handleClick} loading={loading}>{readonly ? '导出' : '保存'}</Button>
                            </div>
                        </div>
                    </Spin>
            }
        </>
    )
}